<?php
header("Content-type: text/xml");

function getpost_ifset($name_test_var, $defval=NULL)
{
  $test_var = $defval;
  if (isset($_POST[$name_test_var]))
  {
    $test_var = $_POST[$name_test_var];
  }
  elseif (isset($_GET[$name_test_var]))
  {
    $test_var = $_GET[$name_test_var];
  }

  return( $test_var );
}

class HTTPRequest
{
  var $_fp;        // HTTP socket
  var $_url;        // full URL
  var $_host;        // HTTP host
  var $_protocol;    // protocol (HTTP/HTTPS)
  var $_uri;        // request URI
  var $_port;        // port

  // scan url
  function _scan_url()
  {
    $req = $this->_url;
    $pos = strpos($req, '://');
    $this->_protocol = strtolower(substr($req, 0, $pos));
    $req = substr($req, $pos+3);
    $pos = strpos($req, '/');
    if($pos === false)
      $pos = strlen($req);
    $host = substr($req, 0, $pos);
    if(strpos($host, ':') !== false)
    {
      list($this->_host, $this->_port) = explode(':', $host);
    }
    else
    {
      $this->_host = $host;
      $this->_port = ($this->_protocol == 'https') ? 443 : 80;
    }
    $this->_uri = substr($req, $pos);
    if($this->_uri == '')
      $this->_uri = '/';
  }
    // constructor
  function HTTPRequest($url)
  {
    $this->_url = $url;
    $this->_scan_url();
  }

  // download URL to string
  function DownloadToString()
  {
    $crlf = "\r\n";
    // generate request
    $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf   .    'Host: ' . $this->_host . $crlf    .    $crlf;
    // fetch
    $this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
    fwrite($this->_fp, $req);
    while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
    $response .= fread($this->_fp, 1024);
    fclose($this->_fp);
    // split header and body
    $pos = strpos($response, $crlf . $crlf);
    if($pos === false)
      return($response);
    $header = substr($response, 0, $pos);
    $body = substr($response, $pos + 2 * strlen($crlf));
    // parse headers
    $headers = array();
    $lines = explode($crlf, $header);
    foreach($lines as $line)
      if(($pos = strpos($line, ':')) !== false)
        $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
    // redirection?
    if(isset($headers['location']))
    {
      $http = new HTTPRequest($headers['location']);
      return($http->DownloadToString($http));
    }
    else
    {
      return($body);
    }
  }
}

function process_request($rss_var)
{
  //$content = utf8_decode(trim($node->content));
  $output = "";
  $dom = new DOMDocument('1.0', 'utf8');
  $dom->preserveWhiteSpace = false;
  $dom->loadXML($rss_var);
  $xpath = new DOMXPath($dom);
  $items = $xpath->query("*/item");

  foreach($items as $item)
  {
    $tmp_doc = new DOMDocument('1.0', 'utf8');
    $tmp_doc->appendChild($tmp_doc->importNode($item,true));
    //$output .= mb_convert_encoding( $tmp_doc->saveHTML(), "HTML-ENTITIES", "utf-8" );
    //$output .= preg_replace( '#%u([0-9A-F]{4})#se','iconv("UTF-16BE","Windows-1251",pack("H4","$1"))', $i );
    $tmp_item = $tmp_doc->saveXML();
    $tmp_item = str_replace( '<?xml version="1.0" encoding="utf8"?>', '', $tmp_item );
    //$tmp_item = html_entity_decode($tmp_item, ENT_COMPAT, "windows-1251");
    //$tmp_item = str_replace( '&', '&amp;', $tmp_item );
    $output .= $tmp_item;
  }
  return ($output);
}

$fulltext = getpost_ifset('fulltext', "1");
$query_meta = getpost_ifset('query_meta', "");
$query_mx = getpost_ifset('query_mx', "");

//$fulltext = 1;
//$query_meta = "%FE%F9%E5%ED%EA%EE";
//$query_mx = "%FE%F9%E5%ED%EA%EE";

$query_mx = iconv('windows-1251', 'utf-8', urldecode($query_mx) );

$meta_handle = new HTTPRequest("http://news.meta.ua/?q=".$query_meta."&rss");
$rss_meta = str_replace( 'windows-1251', 'utf8', iconv('windows-1251', 'utf-8', $meta_handle->DownloadToString()));
$rss_meta = process_request($rss_meta);

$mx_handle = new HTTPRequest("http://api.monitorix.biz/app?c=jGcDJfabZTBTwB&fulltext=".$fulltext."&query=".$query_mx);
$rss_mx = $mx_handle->DownloadToString();
$rss_mx = process_request($rss_mx);

$template =
'<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>Informio.biz media monitor: '.iconv('windows-1251', 'utf-8', urldecode($query_meta)).'</title>
    <link>'.iconv('windows-1251', 'utf-8', urldecode($query_meta)).'</link>
    <description>Informio.</description>
    <ttl>5</ttl>
    <image>
      <url>http://informio.biz/img/h/logo.gif</url>
      <link>http://informio.biz</link>
      <title>Informio.</title>
    </image>'.
    $rss_meta.$rss_mx.
  '</channel>
</rss>';

echo $template;
?>
